package com.onluy.frameworkcloud.tools.utils;

import com.alibaba.fastjson.JSON;
import com.onluy.frameworkcloud.Param.RspInfo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpUtil {



    protected static Logger logger = LoggerFactory.getLogger(HttpUtil.class );



    private static HttpGet getHttpGet(String url, String proxy_ip, int proxy_port){
        RequestConfig requestConfig;
        if(StringUtil.isNotBlank(proxy_ip)) {
            HttpHost proxy = new HttpHost( proxy_ip, proxy_port);
            //创建httpGet实例
            requestConfig = RequestConfig.custom()
                    .setProxy(proxy)
//                .setConnectTimeout(this.connectTimeout)
//                .setSocketTimeout(this.socketTimeout)
//                .setConnectionRequestTimeout(this.connectionRequestTimeout)
                    .build();
        }else{
            requestConfig = RequestConfig.custom()
//                .setConnectTimeout(this.connectTimeout)
//                .setSocketTimeout(this.socketTimeout)
//                .setConnectionRequestTimeout(this.connectionRequestTimeout)
                    .build();
        }
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        //设置请求头消息
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
        httpGet.setHeader("Content-Type", "application/json; charset=UTF-8");
        httpGet.setHeader("Accept", "application/json");
        return httpGet;
    }
    private static HttpGet getHttpGet(String url ){
        return getHttpGet(  url, null, 0);
    }
    private static HttpPost getHttpPost(String url, Object data , String proxy_ip, int proxy_port){
        RequestConfig requestConfig;
        if(StringUtil.isNotBlank(proxy_ip)) {
            HttpHost proxy = new HttpHost( proxy_ip, proxy_port);
            //创建httpGet实例
            requestConfig = RequestConfig.custom()
                    .setProxy(proxy)
//                .setConnectTimeout(this.connectTimeout)
//                .setSocketTimeout(this.socketTimeout)
//                .setConnectionRequestTimeout(this.connectionRequestTimeout)
                    .build();
        }else{
            requestConfig = RequestConfig.custom()
//                .setConnectTimeout(this.connectTimeout)
//                .setSocketTimeout(this.socketTimeout)
//                .setConnectionRequestTimeout(this.connectionRequestTimeout)
                    .build();
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        //设置请求头消息
        httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.setHeader("Accept", "application/json");

        String paramMsg = JSON.toJSONString(data);
        logger.info( "---------post调用请求内容:" + paramMsg);
        if (StringUtil.isNotBlank(paramMsg)) { // 解决中文乱码问题
            StringEntity entity = new StringEntity(paramMsg, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
        }
        return httpPost;
    }
    private static HttpPost getHttpPost(String url, Object data){
        return getHttpPost(  url,data, null, 0);
    }
    private static RspInfo<String> getRspHttpEntity(HttpUriRequest request) throws Exception {
        //创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(request);
        RspInfo<String> respInfo=new RspInfo<String>();
        respInfo.setRspCode(0);
        if (response != null){
            int statusCode =response.getStatusLine().getStatusCode();
            logger.info("------------statusCode:"+ statusCode);
            HttpEntity entity = response.getEntity();  //获取返回实体


            if (statusCode !=  HttpStatus.SC_OK) {
                logger.info("--------代理get调用失败 -------");
                respInfo.setRspCode(statusCode);
                respInfo.setRspDesc("http调用异常statusCode："+statusCode);
            }else{
                logger.info("--------代理get调用成功 -------");

                if (entity != null){
                    respInfo.setRspData(EntityUtils.toString(entity,"utf-8"));
                }

                respInfo.setRspCode(0);
                respInfo.setRspDesc("代理get调用成功");


                logger.info("--------代理get调用返回报文 ：" + respInfo.getRspData());
            }
        }else{
            respInfo.setRspCode(-1);
            respInfo.setRspDesc("--------代理get调用异常:"  );
        }
        if (response != null){
            response.close();
        }
        if (httpClient != null){
            httpClient.close();
        }

        return respInfo;
    }






    public static RspInfo doGetJson(String url, String proxy_ip, int proxy_port) throws Exception {
        RspInfo<String> respInfo=new RspInfo<String>();
        respInfo.setRspCode(0);
        logger.info( "---------代理get调用   URL:" + url);
        HttpGet httpGet= getHttpGet(url,proxy_ip,proxy_port);
        respInfo= getRspHttpEntity( httpGet );
        return  respInfo;

    }



    public static RspInfo doPostJson(String url, Object data , String proxy_ip, int proxy_port) throws Exception {
        RspInfo<String> respInfo=new RspInfo<String>();
        respInfo.setRspCode(0);
        logger.info( "---------代理post调用    URL:" + url);
        HttpPost httpPost= getHttpPost(url,data,proxy_ip,proxy_port);
        respInfo= getRspHttpEntity( httpPost );
        return  respInfo;
    }


    public static RspInfo doGetJson(String url) throws Exception {
        return  doGetJson(url,null,0);
    }


    public static RspInfo doPostJson(String url, Object data) throws Exception {
        return  doPostJson(url,data,null,0);
    }


}
